/* 						-*- coding: utf-8 -*-
* @brief : Une version de environ
* @author : Mathieu RUL
* @version : 1
*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include "environ.h"

char **Environ = NULL;
static unsigned number = 0;
static unsigned sizeEnv = 0;

void init_environ() {
	sizeEnv+=DEFAULT_ALLOC_INCR;
    Environ = calloc(DEFAULT_ALLOC_INCR, sizeof(char*));
    set_environ("HOME", getenv("HOME"));
    set_environ("PATH", "/bin:/usr/bin:/usr/local/bin");
    set_environ("IFS", " \t\n");
    set_environ("PROMPT", "$polysh> ");
    set_environ("TERM", "xterm");
    set_environ("PWD", get_current_dir_name());
    set_environ("SHELL", "Polysh V1");
}

char *get_environ(const char *s) {
    int i = 0;
    if (!Environ) init_environ();
    for ( ; NULL != *(Environ+i); i++) {
        if(0 == strncmp(*(Environ+i), s, strlen(s)-1))
            return strchr(*(Environ+i), '=')+1;
    }
    return "";
}

void  set_environ(const char *var, const char *valeur) {
    int i = 0, find = 0;
    for (; NULL != *(Environ+i); i++) {
         if(0 == strncmp(*(Environ+i), var, strlen(var))) {
            Environ[i] =(char*)realloc(Environ[i], strlen(var)+strlen(valeur)+2);
            sprintf(Environ[i], "%s=%s", var, valeur);
            find = 1;
            break;
        }
    }
    if(!find) {
        if(0 == (number+1)%DEFAULT_ALLOC_INCR && number) {
			sizeEnv+=DEFAULT_ALLOC_INCR;
            Environ = realloc(Environ, (sizeEnv)*sizeof(char *));
			int j;
			for (j=i ; j<sizeEnv ; j++) { Environ[j] = NULL; }
        }
        Environ[i] = (char*)malloc(strlen(var)+strlen(valeur)+2);
        sprintf(Environ[i], "%s=%s", var, valeur);
        number++;
    }
}

void  print_environ(FILE *f) {
    int i;
    if (!Environ) init_environ();
    for (i = 0 ; NULL != *(Environ+i); i++) {
        fprintf(f, "%s\n", *(Environ+i));
    }
}

void add_program_parameters_environ(int argc, char *argv[]) {
    if (!Environ) init_environ();
    unsigned i = 0, all_arg_size = 0;
    char *n = (char*)malloc(2*sizeof(char));
    sprintf(n, "%d", argc);
    set_environ("#", n);
    for(i = 0 ; i < argc; i++) {
        sprintf(n, "%d", i+1);
        set_environ(n, argv[i]);
        all_arg_size += strlen(argv[i]) + 1;
    }
    char *all_arg = (char*)malloc(all_arg_size*sizeof(char));
    for(i = 0; i < argc; i++) {
            strcat (all_arg, argv[i]);
            strcat (all_arg, " ");
    }
    all_arg[all_arg_size-1] = '\0';
    set_environ("*", all_arg);
    free(n);
    free(all_arg);
}
